package spt.mc.demo.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

public class MD5Util {
	protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
			'f' };

	public final static String MD5(String s) {
		if(s.isEmpty()) return "";
		try {
			byte[] strTemp = s.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for(int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return "";
		}
	}

	private MessageDigest md5 = null;

	public MD5Util() {
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {}
	}

	public void update(byte[] buff) {
		this.md5.update(buff, 0, buff.length);
	}

	public void update(byte[] buff, int offset, int len) {
		this.md5.update(buff, offset, len);
	}

	public String MD5() {
		return bufferToHex(md5.digest());
	}

	private String bufferToHex(byte[] bytes) {
		return bufferToHex(bytes, 0, bytes.length);
	}

	private String bufferToHex(byte[] bytes, int offset, int len) {
		StringBuffer stringbuffer = new StringBuffer(2 * len);
		int k = offset + len;
		for(int l = offset; l < k; l++) {
			char c0 = hexDigits[(bytes[l] & 0xf0) >> 4];
			char c1 = hexDigits[bytes[l] & 0xf];
			stringbuffer.append(c0);
			stringbuffer.append(c1);
		}
		return stringbuffer.toString();
	}
	
	@SuppressWarnings("rawtypes")
	public static String createSign(SortedMap<String,Object> parameters,String key,long ts){
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）  
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)) {
            	if(sb.length()>0)
            		sb.append("&"+k + "=" + v);
            	else
            		sb.append(k + "=" + v);
            }
        }
        if(sb.length()>0)
        	sb.append("&signKey=" + key);
        else
        	sb.append("signKey=" + key);
        sb.append("&ts=" + ts);
        System.out.println(sb.toString());
        String sign = MD5(sb.toString()).toUpperCase();
        return sign;
    }
}